<template>
  <div class="map-container">

  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { readPGMFile, handleCreateCanvas } from "../utils";
import { Leafer, Rect, Image } from 'leafer-ui'
const leafer = new Leafer({ view: window, fill: '#fff' })
let originX = ref(0);
let originY = ref(0);
let resolution = ref(0.00)
let mapH = ref(0)
let mapW = ref(0)
// 投射函数 原点坐标 originPoint 分辨率 resolution
function projection(x, y) {
  const screenX = (x - originX.value) / resolution.value;
  const screenY = (y - originY.value) / resolution.value;
  return {
    x: screenX,
    y: mapH.value - screenY
  };
}

function getMapInfo(leafer) {
  axios.get('http://39.96.116.57:8125/getBotMapInfo?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozLCJncm91cF9pZCI6MSwiZXhwIjoxNzQ2ODYwMzk5fQ.5LzVV_M1hKUU1II4qyoQps4wupIxwqrEzSGpbQSQMTA').then(async (res) => {
    let d = res.data.data
    originX.value = d.x
    originY.value = d.y
    resolution.value = d.res
    let imgData = await readPGMFile(d.pgm)
    console.log(imgData)
    // 4. 创建临时的canvas
    let tempCanvas = handleCreateCanvas(imgData)
    const pngUrl = tempCanvas.toDataURL('image/png')
    // 在 LeaferJS 中加载
    const image = new Image({ url: pngUrl })
    image.width = leafer.width
    leafer.add(image)
    setTimeout(() => {
      mapH.value = image.height
      addPower(leafer)
    }, 100)
  })
}
function addPower(leafer) { // 增加充电桩
  let posXY = projection(0, 0)
  console.log(posXY)
  const image = new Image({
    url: '/image/powder.png',
    width: 30,
    height: 30,
    x: posXY.x,
    y: posXY.y,
    draggable: true
  })
  leafer.add(image)
}
onMounted(() => {
  getMapInfo(leafer)
})

</script>
<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
</style>
